<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>======原生的jsonp写法=========</p>
    <button id="btn">发送请求</button>
    <div id="result">
        <span></span>
        <span></span>
    </div>
    <p>======jquery jsonp写法=========</p>
    <button id="sendData">发送请求</button>
    <div id="content">
        <span></span>
        <span></span>
    </div>

    <p>======原生的CORS写法=========</p>
    <div>
        <button id="getCORS">发送请求</button>
        <div id="contentCORS">
            <span></span>
            <span></span>
        </div>
    </div>
    <!-- 原生的jsonp写法 -->
        <script>
           function handle(data){
                console.log("JSONP请求数据：",data);
                var span = document.getElementsByTagName('span')
                var {name,age} = data
                span[0].textContent = name
                span[1].textContent = age
            }
        </script>

        <script>
            const btn = document.getElementById('btn')
            btn.onclick = function(){
                var script = document.createElement('script')
                script.src = "http://127.0.0.1:8000/getJSONP"
                document.body.appendChild(script)
            }
        </script>

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $('#sendData').click(function(){
        console.log('8989');
        $.getJSON('http://127.0.0.1:8000/getJQJSONP?callback=?',function(data){
            console.log("data=",data);
            console.log("sss=",$('#content span'));
            var span = $('#content span')
            var {name,age} = data
            span[0].innerText = name
            span[1].innerText = age

        })
    })

</script>

<!-- CORS -->
<script>
    var corsBTN = document.getElementById('getCORS')
    var url = `http://127.0.0.1:8000/getCORS?${Date()}`
    corsBTN.onclick = function(){
        console.log('222');
        var xhr = new XMLHttpRequest()
        xhr.open('GET',url)
        xhr.send()
        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4) {
                if (xhr.status >=200 && xhr.status < 300) {
                    console.log('数据',xhr.response);
                    let {name,age} = JSON.parse(xhr.response)
                    var span = $('#contentCORS span')
                    // var span = document.getElementsByTagName('')
                    span[0].innerText = name
                    span[1].innerText = age
                }
            }
        }
    }
</script>
</body>
</html>